package shutdown

import (
	"os"
	"os/signal"
	"sync"
	"syscall"

	"github.com/mars/pkg/loggers"
)

const Name = "PosixSignalManager"

type PosixSignalManager struct {
	signals []os.Signal
}

var _ ShutdownManager = (*PosixSignalManager)(nil)

func NewPosixSignalManager(sig ...os.Signal) *PosixSignalManager {
	if len(sig) == 0 {
		sig = make([]os.Signal, 2)
		sig[0] = os.Interrupt
		sig[1] = syscall.SIGTERM
	}

	return &PosixSignalManager{
		signals: sig,
	}
}

// GetName returns name of this ShutdownManager.
func (posixSignalManager *PosixSignalManager) GetName() string {
	return Name
}

// Start starts listening for posix signals.
func (posixSignalManager *PosixSignalManager) ListenShutdown(gs GSInterface) error {
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		c := make(chan os.Signal, 1)
		signal.Notify(c, posixSignalManager.signals...)

		// Block until a signal is received.
		<-c

		gs.DoShutdown(posixSignalManager)
	}()
	wg.Wait()
	return nil
}

func (posixSignalManager *PosixSignalManager) ShutdownStart() error {
	loggers.Info("PosixSignalManager shutdwon start......")
	return nil
}

// ShutdownFinish exits the app with os.Exit(0).
func (posixSignalManager *PosixSignalManager) ShutdownFinish() error {
	loggers.Info("PosixSignalManager shutdwon finished......")
	os.Exit(0)
	return nil
}
